﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SSN.DotNet;
using SSN.BusinessFramework;
using SSN.WebFramework;
using SSN.BusinessFramework.Accounts;

namespace SSN.WebFramework.Controls
{
    public class AccountLabel : System.Web.UI.WebControls.Label,IBindable
    {
        public string AccountText { get; set; }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (!string.IsNullOrEmpty(AccountText))
            {
                AuthPage page = (AuthPage) Page;
                AccountManager accMgr = new AccountManager(page.SecurityManager.SecurityContext);
			 Account account = new Account();
                if (account.Load(page.SecurityManager.SecurityContext,AccountText,!AccountText.ToUpper().StartsWith("SN")))
                {
                    Text = string.Format("<a href='/account/details.aspx{0}'>{1}</a>", page.ParameterManager.EncryptQueryString("?snnumber=" + account.SNNumber), account.SNNumber);
                }
            }

            base.Render(writer);
        }

	   public string BindProperty { get; set; }

        public string BindTranslator { get; set; }

	   public void BindFromObject(object obj) {
		   PropertyInfo info=obj.GetType().GetProperty(BindProperty);
		   if(info!=null) {
			   if(!string.IsNullOrEmpty(BindTranslator)) {
				   MethodInfo mInfo = Page.GetType().GetMethod(BindTranslator);
				   if(mInfo != null) {
					   this.Text = (string)mInfo.Invoke(obj,null);
				   }
			   }
			   else {
				   object v = info.GetValue(obj,null);
				   if(v != null) {
					   this.AccountText = v.ToString().Trim();
				   }
			   }
		   }
	   }


	   public void BindToObject(object obj) {
		   PropertyInfo info=obj.GetType().GetProperty(BindProperty);
		   if(info!=null) {
			   info.SetValue(obj,Convert.ChangeType(this.AccountText,info.PropertyType),null);
		   }
	   }
    }
}
